<template>
  <div>
    <!-- 头部搜索 -->
    <div class="dskt_nav_bar" v-if="viewType=='add'">
      <div class="bar_span bar_left">
        <img @click="searchEnterEvent" :src="'./static/img/icon_search.png'">
      </div>
      <div class="bar_center">
        <input
          type="text"
          class="base_input"
          v-model="searchData.searchKey"
           ref="inputText" 
          @input="searchInputEvent"
          @keyup.enter="searchEnterEvent"
          placeholder="姓名、学号、宿舍号、班级号"
        >
      </div>
      <div class="bar_span bar_right click_to_green" @click="doOpenErCode">
        <img
          :src="[view.isShowSearch?'./static/img/Btn-DeletePic.png':'./static/img/btn-scan.png']"
        >
      </div>
    </div>
    <!--end 头部搜索 -->
    <div class="list_title">
      <span class="green_span_title">{{viewType=='add'?'已选学生':'共'}} 
        <span
          class="color_primary"
        >{{view.isShowSearch?serverData.searchSelectNum:serverData.selectUserList.length}}</span> 人
      </span>
    </div>
    <!-- 已经选择的用户的用户-->
    <swipeout v-if="!view.isShowSearch">
      <swipeout-item
        transition-mode="follow"
        v-for="(stu,index) in serverData.selectUserList"
        :key="index"
      >
        <div slot="right-menu" v-if="viewType=='add'">
          <swipeout-button @click.native="doDeleteSelect(index)" type="warn">删除</swipeout-button>
        </div>
        <div slot="content" class="green-box user_box vux-1px-t click_to_green">
          <flexbox :gutter="0" align="flex-start" class="kaidan_box_top">
            <flexbox-item :span="3/11" class="user_img" align="center">
              <x-img :src="stu.headImg" :default-src="stu.headImg"></x-img>
            </flexbox-item>
            <flexbox-item class="stu_msg">
              <div class="user_name">{{stu.name}}</div>
              <div class="user_class">
                <span>{{stu.departmentName}}</span>
                <span>{{stu.majorName}} {{stu.schoolYearName}}</span>
              </div>
              <div class="user_address">
                <span>{{stu.no}}</span>
                <span>{{stu.showAddress}}</span>
              </div>
            </flexbox-item>
          </flexbox>
        </div>
      </swipeout-item>
    </swipeout>

    <div class="scrollerWrap" v-if="view.isShowSearch">
      <scroller :on-infinite="infinite" ref="user_scroller">
        <div class="searchList">
          <div
            slot="content"
            v-for="(stu,index) in serverData.searchUserList"
            :key="index"
            class="green-box user_box vux-1px-t click_to_green"
            @click="searchBoxClick(index)"
          >
            <flexbox :gutter="0" class="kaidan_box_top">
              <flexbox-item :span="1/15" class="check_div">
                <icon type="zhengque" :class="[stu.checked ? 'color_primary' : 'color_unselect']"/>
              </flexbox-item>
              <flexbox-item :span="3/11" class="user_img" align="center">
                <x-img :src="stu.headImg" :default-src="stu.headImg"></x-img>
              </flexbox-item>
              <flexbox-item class="stu_msg">
                <div class="user_name">{{stu.name}}</div>
                <div class="user_class">
                  <span>{{stu.departmentName}}</span>
                  <span>{{stu.majorName}} {{stu.schoolYearName}}</span>
                </div>
                <div class="user_address">
                  <span>{{stu.no}}</span>
                  <span>{{stu.showAddress}}</span>
                </div>
              </flexbox-item>
            </flexbox>
          </div>
        </div>
      </scroller>
    </div>
    <!--end  已经选择的用户 -->
    <!-- 底部的确定 -->
    <div class="buttom_div" v-if="viewType=='add'">
      <table>
        <tr>
          <td v-if="view.isShowSearch" class="buttom_select click_to_green" @click="doSelectAll()">
            <icon type="zhengque" :class="[view.isSelectAll ? 'color_primary' : 'color_unselect']"/>
            <span>全选</span>
          </td>
          <td class="buttom_btn_box">
            <x-button type="primary" @click.native="doOk" class="dskt_btn">确定</x-button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
import userService from "../../shared/service/userService";
import weixinService from "../../shared/service/weixinService";
const wx = require('weixin-js-sdk')

import { Swipeout, SwipeoutItem, SwipeoutButton, XImg } from "vux";

export default {
  components: {
    Swipeout,
    SwipeoutItem,
    SwipeoutButton,
    XImg
  },
  data() {
    var data = {
      viewType: this.$route.query.viewType
    };
    data.view = {
      isSelectAll: false,
      isShowSearch: false
    };
    data.searchData = {
      searchKey: "",
      startTime: "",
      endime: ""
    };
    data.serverData = {
      searchUserList: [],
      searchSelectNum: 0,
      selectUserList: this.$dbUtil.get(this.$dbUtil.key.SELECT_USER_LIST)
    };
    data.userPage = {
      pageNum: 0,
      pages: 0
    };
    return data;
  },
  mounted() {
    //页面滚动给顶部的搜索栏添加一个样式
    $(".view-router").on("scroll", function() {
      if ($(this).scrollTop() >= 100) {
        $(".dskt_nav_bar").addClass("bar_sroll");
      } else {
        $(".dskt_nav_bar").removeClass("bar_sroll");
      }
    });
    if (this.viewType != "add") {
      document.title = '考核学生';
      $(".view-router").css("padding-top", "0px");
    }else{
      this.initWx();
    }

  },
  methods: {
    initWx() {
      var url = location.href;
      weixinService.getSignature(url).then(res => {
        if (res.data) {
          var data = res.data;
          wx.config({
            debug: false,
            appId: data.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature, // 必填，签名，见附录1
            jsApiList: ["scanQRCode"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
          });
        }
      });
    },
    wxScanQRCode() {
      var _this = this;
   /*     var result="bed_b2387693c2d1441488463c6a3a9e7c92";
      result="dormitory_e7c39de558784fe3a86e926438c86787";
          this.dealRQ(result);
return;   */
        wx.scanQRCode({
          needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
          scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
          success: function(res) {
            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
            _this.dealRQ(result);
           
          },
          error:function(res){
             _this.$vux.toast.text("微信失败 "+res);
          }
        });
    },
    dealRQ(result){
      var _this = this;
      if(result.indexOf("bed_") >-1 ){
          var id =    result.replace("bed_","");
          var param = {
            bedId:id,
            studentCheckInState:1,
          }
          userService.selectableStudent(param).then(res => {
            var data = res.data.list;
            let list = [];
            if(data.length==0){
               this.$vux.toast.text("未识别到学生信息");
            }
            for (let i = 0; i < data.length; i++) {
                let element = data[i];
                element.showAddress = this.$commonUtil.getUserAddress(element);
                element.studentFileId = element.id;
                element.checked = false;
                if(!element.headImg){
                  element.headImg = './static/img/avatar_default.png';
                }
                //如果在已经选择的里面
                if( this.$commonUtil.isInArr( this.serverData.selectUserList,'id',element.id) ){

                }else{
                  list.push(element);
                }
            }
            this.serverData.selectUserList=this.serverData.selectUserList.concat(list);
            this.initSearchSelectNum();
          });
       }else if(result.indexOf("dormitory_") >-1 ){
          var id =    result.replace("dormitory_","");
          var param = {
            dormitoryId:id,
             studentCheckInState:1,
          }
          userService.selectableStudent( param).then(res => {
            var data = res.data.list;
            let list = [];
            if(data.length==0){
               this.$vux.toast.text("未识别到学生信息");
            }
            for (let i = 0; i < data.length; i++) {
                let element = data[i];
                element.showAddress = this.$commonUtil.getUserAddress(element);
                element.studentFileId = element.id;
                element.checked = false;
                if(!element.headImg){
                  element.headImg = './static/img/avatar_default.png';
                }

                //如果在已经选择的里面
                if( this.$commonUtil.isInArr( this.serverData.selectUserList,'id',element.id) ){

                }else{
                  list.push(element);
                }
            }
            this.serverData.selectUserList=this.serverData.selectUserList.concat(list);
        //      this.serverData.searchUserList = this.serverData.searchUserList.concat(list);
            this.initSearchSelectNum();
          });
       }else{
          this.$vux.toast.text("未识别到学生信息");
       }
    },
    //输入框点击事件
    searchInputEvent() {
      if (!this.searchData.searchKey) {
        this.view.isShowSearch = false;
      }else{
        this.view.isShowSearch = true;
        this.doSearchUser(1);
      }
    },
    //输入框回车事件
    searchEnterEvent() {
      if (!this.searchData.searchKey) {
        this.$vux.toast.text("请输入");
        return;
      }
      this.$refs.inputText.blur();
      this.view.isShowSearch = true;
      this.doSearchUser(1);
    },
    //打开二维码
    doOpenErCode(viewType, id) {
      //如果是搜索页面
      if (this.view.isShowSearch) {
        this.searchData.searchKey = "";
        this.view.isShowSearch = false;
      } else {
        this.wxScanQRCode();
        //   this.$vux.toast.text("二维码开发中");
      }
    },
    //打开二维码
    doOk() {
      //如果是搜索页面
      if (this.view.isShowSearch) {
        for (let i = 0; i < this.serverData.searchUserList.length; i++) {
          let element = this.serverData.searchUserList[i];
          //如果在里面取消了
          if(element.isin && !element.checked){
            var index = this.$commonUtil.getInArrIndex(this.serverData.selectUserList,'id',element.id);
            if(index>-1){
                this.serverData.selectUserList.splice(index, 1);
            }
          }
          if (
            element.checked &&
            !this.$commonUtil.isInArr(
              this.serverData.selectUserList,
              "id",
              element.id
            )
          ) {
            //判断是否在列表里了
            this.serverData.selectUserList.push(element);
          }
        }
        this.view.isShowSearch = false;
        this.searchData.searchKey = "";
      } else {
        //如果是选择了学生确认时间
        if (this.serverData.selectUserList.length <= 0) {
          this.$vux.toast.text("请选择学生");
          return;
        }
        //把选择的用户保存到数据库中
        this.$dbUtil.set(
          this.$dbUtil.key.SELECT_USER_LIST,
          this.serverData.selectUserList
        );
        //把上一页传过来的东西保存到数据库 证明 数据成功了
        this.$dbUtil.set(
          this.$dbUtil.key.SELECT_USER_VIEW,
          this.$route.query.toNextViewOkFlag
        );

        this.$router.back(-1);
      }
    },
    //删除选择的
    doDeleteSelect(i) {
      this.serverData.selectUserList.splice(i, 1);
      this.$vux.toast.text("已删除");
    },
    doSearchUser(page, fn,bedId,dormitoryId) {
      var param = { 
        searchKey: this.searchData.searchKey,
        studentCheckInState:1
       };
       if(dormitoryId){
         param.dormitoryId=dormitoryId;
         param.searchKey="";
       }
       if(bedId){
         param.bedId=bedId;
         param.searchKey="";
       }
      userService.getUesrPage(page, param).then(res => {
        var data = res.data;
        this.userPage.pageNum = page;
        this.userPage.pages = data.pages;
 
        let list = [];
        for (let i = 0; i < data.list.length; i++) {
          let element = data.list[i];
          element.showAddress = this.$commonUtil.getUserAddress(element);
          element.studentFileId = element.id;
          //如果在已经搜索的列表中
          if(  this.$commonUtil.isInArr( this.serverData.selectUserList, "id",  element.id ) ){
            element.checked = true;
            element.isin = true;
          }else{
            element.checked = false;
            element.isin = false;
          }
          if(!element.headImg){
            element.headImg = './static/img/avatar_default.png';
          }
          list.push(element);
        }
        if (page == 1) {
          this.serverData.searchUserList = list;
        } else {
          this.serverData.searchUserList = this.serverData.searchUserList.concat(
            list
          );
        }
        this.view.isSelectAll=false;
        this.initSearchSelectNum();
        if (fn) fn();
      });
    },
    //搜索出来的用户点击
    searchBoxClick(i) {
      this.serverData.searchUserList[i].checked = !this.serverData
        .searchUserList[i].checked;
      this.initSearchSelectNum();
    },
    initSearchSelectNum() {
      var num = 0;
      for (let i = 0; i < this.serverData.searchUserList.length; i++) {
        var element = this.serverData.searchUserList[i];
        if (element.checked) {
          num++;
        }
      }
      this.serverData.searchSelectNum = num;
    },
    //点击全选
    doSelectAll() {
      var isHasAllSelect = false;
      for (let i = 0; i < this.serverData.searchUserList.length; i++) {
        var element = this.serverData.searchUserList[i];
        if (!element.checked) {
          isHasAllSelect = true;
          break;
        }
      }
      this.view.isSelectAll = isHasAllSelect;
      for (let i = 0; i < this.serverData.searchUserList.length; i++) {
        this.serverData.searchUserList[i].checked = isHasAllSelect;
      }
      this.initSearchSelectNum();
    },
    //下拉刷新
    refresh(done) {},
    //下拉刷新
    infinite(done) {
      console.log("触发下拉-=------------");
      if (
        this.userPage.pages > 0 &&
        this.userPage.pages <= this.userPage.pageNum
      ) {
        this.$refs.user_scroller.finishInfinite(true);
        return;
      }
      if (this.userPage.pages == 0) {
        this.$refs.user_scroller.finishInfinite(true);
        return;
      }
      //    this.$refs.user_scroller.finishInfinite(false);
      this.doSearchUser(this.userPage.pageNum + 1, done);
    }
  }
};
</script>
<style scoped>
</style>
<style scoped>
.scrollerWrap {
  position: absolute;
  width: 100%;
  top: 75px;
  bottom: 75px;
}

/* 滚动的样式 */
.bar_sroll {
  border-bottom: 1px solid #e3e3e3;
}
.view-router {
  padding-top: 43px;
  padding-bottom: 60px !important;
}
.buttom_div {
  width: 100%;
  height: 60px;
  position:fixed;
  z-index: 99999;
  bottom: 0;
  background: rgba(242, 251, 254, 1);
  box-sizing: border-box;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.08);
  padding: 0 15px;
}
.buttom_div table {
  width: 100%;
  height: 100%;
}
.buttom_div .buttom_select {
  width: 40%;
  font-size: 17px;
}
.buttom_div .buttom_select .weui-icon {
  font-size: 20px;
}
.buttom_select .buttom_btn_box {
  padding: 0 15px;
}
</style>
